﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KBManagement.DAL;
using KBManagement.BIZ;
using KBManagement.Library;

namespace KBManagement.BIZ
{
    class StoreTempFacade : FacadeBase<StoreTemp>
    {


        public override IQueryable Select()
        {
            var storeTemp = from fc in Utils.CreateInstance().GetDBContext().StoreTemps
                            select new
                            {
                                fc.ID,
                                fc.Store.S_Name
                            };
            return storeTemp;
        }

        public override StoreTemp[] SelectEntities()
        {
            throw new NotImplementedException();
        }

        public override StoreTemp Find(object id)
        {
            return Library.Utils.CreateInstance().GetDBContext().StoreTemps.SingleOrDefault(x => x.ID.Equals(id));
        }

        public override StoreTemp[] FindMany(object id)
        {
            throw new NotImplementedException();
        }

        public Boolean AddService(Food food, int quantity)
        {
            foreach (FoodComponent fComponent in food.FoodComponents)
            {
                int qtity = Convert.ToInt32(fComponent.ComQuantilty) * quantity;
                if (qtity > 0)
                {
                    if (!update(fComponent.StoreTempId.ToString(), qtity, "add"))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        public Boolean DeleteService(Food food, int quantity)
        {
            foreach (FoodComponent fComponent in food.FoodComponents)
            {
                int qtity = Convert.ToInt32(fComponent.ComQuantilty) * quantity;
                update(fComponent.StoreTempId.ToString(), qtity, "delete");
            }
            return true;
        }

        public Boolean update(string id,int quantity,string str)
        {
            KBSQLClassDataContext context = new KBSQLClassDataContext();
            StoreTemp storeTemp = context.StoreTemps.SingleOrDefault(x => x.ID == id);
            if (str.Equals("add"))
            {
                if (storeTemp.Quantity < quantity)
                {
                    return false;
                }
                storeTemp.Quantity = storeTemp.Quantity - quantity;
                context.SubmitChanges();
            }
            else if (str.Equals("delete"))
            {
                if (storeTemp.Quantity <= 0)
                {
                    storeTemp.Quantity = quantity;
                }
                else
                {
                    storeTemp.Quantity = storeTemp.Quantity + quantity;
                    
                }
                context.SubmitChanges();
            }
            return true;
        }

    }
}
